/*
 *      Copyright (c) 2009-2010 nord
 *
 *      Web: http://mediaplayersite.com/YAYMan
 *
 *      This software is licensed under a Creative Commons License
 *      See this page: http://creativecommons.org/licenses/by-nc/3.0/
 *
 *      For any reuse or distribution, you must make clear to others the
 *      license terms of this work.
 */

/*
 * EditLibraryFrame.java
 *
 * Created on Feb 5, 2010, 2:20:54 PM
 */

package yayman;

import javax.xml.parsers.*;
import org.jdesktop.application.Action;
import org.w3c.dom.*;
import java.io.*;
import java.util.*;

import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.swing.*;
import javax.swing.JOptionPane;

public class EditLibraryFrame extends javax.swing.JDialog {
    private File libraryFile;
    private String nmtIP;
    private DefaultListModel libs;
    private PopAPI popAPI;
    private final String excludeNames = "sample,tmp/,temp/,RECYCLER/,RECYCLE.BIN/";
    SetupWizardBasicFrame basicWizard;
    private boolean helpPlayerPath = true;
    //private final String localPathRoot = "/action/jukebox.jsp?absolutepath=";

    /** Creates new form EditLibraryFrame */
    public EditLibraryFrame(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public EditLibraryFrame(java.awt.Frame parent, boolean modal, String libraryfile) {
        this(parent, modal, new File(libraryfile));
    }

    public EditLibraryFrame(java.awt.Frame parent, boolean modal, File libraryfile) {
        this(parent, modal);

        libraryFile = libraryfile;
        this.setTitle("Editing Library File: "+libraryFile.getName());
        nmtIP = null;
        popAPI = null;
        basicWizard = null;
        loadLibrary();
        togglePlayerPathOptions();
    }

    public EditLibraryFrame (java.awt.Frame parent, boolean modal, SavedJukebox jb) {
        this(parent, modal, jb.getLibraryFile());
        nmtIP = jb.getNmt().getAddress();
        if (nmtIP != null && !nmtIP.isEmpty()) {
            popAPI = new PopAPI(nmtIP);
            setOptionsFromIP();
        }
    }

    public EditLibraryFrame (java.awt.Frame parent, SavedJukebox jb, SetupWizardBasicFrame bWizard) {
        this(parent, true, jb);
        basicWizard = bWizard;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        libraryMenu = new javax.swing.JPopupMenu();
        addDirMenu = new javax.swing.JMenuItem();
        removeDirMenu = new javax.swing.JMenuItem();
        fileChooser = new javax.swing.JFileChooser();
        pathTypeGroup = new javax.swing.ButtonGroup();
        myiHomePop = new javax.swing.JPopupMenu();
        myiHomePopChooseMenu = new javax.swing.JMenuItem();
        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        libList = new javax.swing.JList();
        jPanel2 = new javax.swing.JPanel();
        pathTxt = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        descTxt = new javax.swing.JTextField();
        saveBtn = new javax.swing.JButton();
        cancelBtn = new javax.swing.JButton();
        btnSaveDir = new javax.swing.JButton();
        radiHome = new javax.swing.JRadioButton();
        radUSB = new javax.swing.JRadioButton();
        radHD = new javax.swing.JRadioButton();
        cmbUSB = new javax.swing.JComboBox();
        radNetwork = new javax.swing.JRadioButton();
        jLabel1 = new javax.swing.JLabel();
        cmbHD = new javax.swing.JComboBox();
        cmbNetwork = new javax.swing.JComboBox();
        radPC = new javax.swing.JRadioButton();
        jLabel2 = new javax.swing.JLabel();
        playerPathTxt = new javax.swing.JTextField();
        radEvUSB = new javax.swing.JRadioButton();
        cmbEvUSB = new javax.swing.JComboBox();

        libraryMenu.setName("libraryMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(yayman.YAYManApp.class).getContext().getActionMap(EditLibraryFrame.class, this);
        addDirMenu.setAction(actionMap.get("addLibraryDir")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(yayman.YAYManApp.class).getContext().getResourceMap(EditLibraryFrame.class);
        addDirMenu.setIcon(resourceMap.getIcon("addDirMenu.icon")); // NOI18N
        addDirMenu.setText(resourceMap.getString("addDirMenu.text")); // NOI18N
        addDirMenu.setToolTipText(resourceMap.getString("addDirMenu.toolTipText")); // NOI18N
        addDirMenu.setName("addDirMenu"); // NOI18N
        libraryMenu.add(addDirMenu);

        removeDirMenu.setAction(actionMap.get("removeLibraryDir")); // NOI18N
        removeDirMenu.setIcon(resourceMap.getIcon("removeDirMenu.icon")); // NOI18N
        removeDirMenu.setText(resourceMap.getString("removeDirMenu.text")); // NOI18N
        removeDirMenu.setToolTipText(resourceMap.getString("removeDirMenu.toolTipText")); // NOI18N
        removeDirMenu.setName("removeDirMenu"); // NOI18N
        libraryMenu.add(removeDirMenu);

        fileChooser.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);
        fileChooser.setName("fileChooser"); // NOI18N

        myiHomePop.setName("myiHomePop"); // NOI18N

        myiHomePopChooseMenu.setAction(actionMap.get("selectDirectory")); // NOI18N
        myiHomePopChooseMenu.setIcon(resourceMap.getIcon("myiHomePopChooseMenu.icon")); // NOI18N
        myiHomePopChooseMenu.setText(resourceMap.getString("myiHomePopChooseMenu.text")); // NOI18N
        myiHomePopChooseMenu.setName("myiHomePopChooseMenu"); // NOI18N
        myiHomePop.add(myiHomePopChooseMenu);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        setResizable(false);

        jSplitPane1.setDividerLocation(150);
        jSplitPane1.setName("jSplitPane1"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        libList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        libList.setComponentPopupMenu(libraryMenu);
        libList.setName("libList"); // NOI18N
        libList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                libListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(libList);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 346, Short.MAX_VALUE)
        );

        jSplitPane1.setLeftComponent(jPanel1);

        jPanel2.setName("jPanel2"); // NOI18N

        pathTxt.setEditable(false);
        pathTxt.setText(resourceMap.getString("pathTxt.text")); // NOI18N
        pathTxt.setToolTipText(resourceMap.getString("pathTxt.toolTipText")); // NOI18N
        pathTxt.setComponentPopupMenu(myiHomePop);
        pathTxt.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        pathTxt.setName("pathTxt"); // NOI18N
        pathTxt.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                pathTxtMouseClicked(evt);
            }
        });

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        descTxt.setText(resourceMap.getString("descTxt.text")); // NOI18N
        descTxt.setToolTipText(resourceMap.getString("descTxt.toolTipText")); // NOI18N
        descTxt.setName("descTxt"); // NOI18N

        saveBtn.setAction(actionMap.get("saveClose")); // NOI18N
        saveBtn.setText(resourceMap.getString("saveBtn.text")); // NOI18N
        saveBtn.setToolTipText(resourceMap.getString("saveBtn.toolTipText")); // NOI18N
        saveBtn.setName("saveBtn"); // NOI18N

        cancelBtn.setAction(actionMap.get("cancelClose")); // NOI18N
        cancelBtn.setText(resourceMap.getString("cancelBtn.text")); // NOI18N
        cancelBtn.setToolTipText(resourceMap.getString("cancelBtn.toolTipText")); // NOI18N
        cancelBtn.setName("cancelBtn"); // NOI18N

        btnSaveDir.setAction(actionMap.get("saveLibraryDir")); // NOI18N
        btnSaveDir.setText(resourceMap.getString("btnSaveDir.text")); // NOI18N
        btnSaveDir.setToolTipText(resourceMap.getString("btnSaveDir.toolTipText")); // NOI18N
        btnSaveDir.setName("btnSaveDir"); // NOI18N

        radiHome.setAction(actionMap.get("togglePlayerPathOptions")); // NOI18N
        pathTypeGroup.add(radiHome);
        radiHome.setSelected(true);
        radiHome.setText(resourceMap.getString("radiHome.text")); // NOI18N
        radiHome.setToolTipText(resourceMap.getString("radiHome.toolTipText")); // NOI18N
        radiHome.setName("radiHome"); // NOI18N

        radUSB.setAction(actionMap.get("togglePlayerPathOptions")); // NOI18N
        pathTypeGroup.add(radUSB);
        radUSB.setText(resourceMap.getString("radUSB.text")); // NOI18N
        radUSB.setToolTipText(resourceMap.getString("radUSB.toolTipText")); // NOI18N
        radUSB.setName("radUSB"); // NOI18N

        radHD.setAction(actionMap.get("togglePlayerPathOptions")); // NOI18N
        pathTypeGroup.add(radHD);
        radHD.setText(resourceMap.getString("radHD.text")); // NOI18N
        radHD.setToolTipText(resourceMap.getString("radHD.toolTipText")); // NOI18N
        radHD.setName("radHD"); // NOI18N

        cmbUSB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "USB_DRIVE_A-1", "USB_DRIVE_B-1", "USB_DRIVE_C-1", "USB_DRIVE_D-1" }));
        cmbUSB.setName("cmbUSB"); // NOI18N

        radNetwork.setAction(actionMap.get("togglePlayerPathOptions")); // NOI18N
        pathTypeGroup.add(radNetwork);
        radNetwork.setText(resourceMap.getString("radNetwork.text")); // NOI18N
        radNetwork.setToolTipText(resourceMap.getString("radNetwork.toolTipText")); // NOI18N
        radNetwork.setName("radNetwork"); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        cmbHD.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "HARD_DISK", "SATA_DISK", "SATA_DISK_A1", "SATA_DISK_B1" }));
        cmbHD.setName("cmbHD"); // NOI18N

        cmbNetwork.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Share_Name" }));
        cmbNetwork.setName("cmbNetwork"); // NOI18N

        radPC.setAction(actionMap.get("togglePlayerPathOptions")); // NOI18N
        pathTypeGroup.add(radPC);
        radPC.setText(resourceMap.getString("radPC.text")); // NOI18N
        radPC.setToolTipText(resourceMap.getString("radPC.toolTipText")); // NOI18N
        radPC.setName("radPC"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        playerPathTxt.setText(resourceMap.getString("playerPathTxt.text")); // NOI18N
        playerPathTxt.setToolTipText(resourceMap.getString("playerPathTxt.toolTipText")); // NOI18N
        playerPathTxt.setName("playerPathTxt"); // NOI18N

        radEvUSB.setAction(actionMap.get("togglePlayerPathOptions")); // NOI18N
        pathTypeGroup.add(radEvUSB);
        radEvUSB.setText(resourceMap.getString("radEvUSB.text")); // NOI18N
        radEvUSB.setToolTipText(resourceMap.getString("radEvUSB.toolTipText")); // NOI18N
        radEvUSB.setName("radEvUSB"); // NOI18N

        cmbEvUSB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "USB_NAME" }));
        cmbEvUSB.setName("cmbEvUSB"); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(20, 20, 20)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(playerPathTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE)
                            .addComponent(pathTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE)
                            .addComponent(descTxt, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGap(57, 57, 57)
                                .addComponent(saveBtn)
                                .addGap(18, 18, 18)
                                .addComponent(cancelBtn))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(radHD)
                                    .addComponent(radNetwork))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(cmbNetwork, 0, 163, Short.MAX_VALUE)
                                    .addComponent(cmbHD, 0, 163, Short.MAX_VALUE)))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(radUSB)
                                .addGap(10, 10, 10)
                                .addComponent(cmbUSB, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(radEvUSB)
                                .addGap(18, 18, 18)
                                .addComponent(cmbEvUSB, 0, 163, Short.MAX_VALUE))
                            .addComponent(radiHome)
                            .addComponent(radPC))
                        .addGap(58, 58, 58))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(btnSaveDir)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(descTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pathTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(14, 14, 14)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(playerPathTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radUSB)
                    .addComponent(cmbUSB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radHD)
                    .addComponent(cmbHD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radNetwork)
                    .addComponent(cmbNetwork, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radEvUSB)
                    .addComponent(cmbEvUSB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(radiHome)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(radPC)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnSaveDir)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveBtn)
                    .addComponent(cancelBtn))
                .addContainerGap())
        );

        jSplitPane1.setRightComponent(jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 526, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void libListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_libListValueChanged
        if (libList.getSelectedIndex() != -1) {
            //removeDirMenu.setEnabled(true);
            
            helpPlayerPath = false;
            NMTLibrary lib = (NMTLibrary)libList.getSelectedValue();
            descTxt.setText(lib.getDescription());
            pathTxt.setText(lib.getPath());
            playerPathTxt.setText(lib.getPlayerPath());
            radPC.setSelected(true);
            helpPlayerPath = true;
        } else {
            removeDirMenu.setEnabled(false);
        }
        removeDirMenu.setEnabled(libList.getModel().getSize() > 1 && libList.getSelectedIndex() != -1);
    }//GEN-LAST:event_libListValueChanged

    private void pathTxtMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pathTxtMouseClicked
        showComponentPopup(pathTxt,evt);
    }//GEN-LAST:event_pathTxtMouseClicked

    /**
    * @param args the command line arguments
    */
    /*public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                EditLibraryFrame dialog = new EditLibraryFrame(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }*/

    public void loadLibrary() {
        libs = new DefaultListModel();
        List<NMTLibrary> libraries = JukeboxInterface.getLibraries(libraryFile);

        for (int i = 0; i < libraries.size(); i++) {
            libs.addElement(libraries.get(i));
        }
        libList.setModel(libs);
        libListValueChanged(null);
        if (libs.getSize() > 0) {
            libList.setSelectedIndex(0);
        } else {
            addLibraryDir();
        }
    }

    @Action
    public void cancelClose() {
        if (basicWizard != null) {
            basicWizard.updateLibraryStatus();
        }
        this.setVisible(false);
    }

    @Action
    public void saveClose() {
        //if (libList.getModel().getSize() == 0 && !pathTxt.getText().isEmpty()) addLibraryDir();
        if (libList.getModel().getSize() > 0) {
            try {
                Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
                Element rootEle = doc.createElement("libraries");
                Element libEle, pathEle, playerPathEle, excludeEle, descEle, prebufEle, scrapeEle;
                doc.appendChild(rootEle);
                NMTLibrary lib;
                
                for(int i = 0; i < libs.size(); i++) {
                    lib = (NMTLibrary)libs.get(i);
                    if (lib.getPath() == null || lib.getPath().isEmpty() || lib.getPlayerPath() == null || lib.getPlayerPath().isEmpty()) continue;
                    libEle = doc.createElement("library");
                    rootEle.appendChild(libEle);
                    
                    pathEle = doc.createElement("path");
                    playerPathEle = doc.createElement("playerpath");
                    excludeEle = doc.createElement("exclude");
                    excludeEle.setAttribute("name", excludeNames);
                    descEle = doc.createElement("description");
                    prebufEle = doc.createElement("prebuf");
                    scrapeEle = doc.createElement("scrapeLibrary");

                    
                    pathEle.setTextContent(lib.getPath());
                    libEle.appendChild(pathEle);
                    playerPathEle.setTextContent(lib.getPlayerPath());
                    libEle.appendChild(playerPathEle);
                    if (!lib.getDescription().equals("")) {
                        descEle.setTextContent(lib.getDescription());
                        libEle.appendChild(descEle);
                    } else {
                        descEle.setTextContent("");
                    }
                    libEle.appendChild(excludeEle);
                    prebufEle.setTextContent("");
                    libEle.appendChild(prebufEle);
                    scrapeEle.setTextContent("true");
                    libEle.appendChild(scrapeEle);
                }
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                DOMSource source = new DOMSource(doc);
                StreamResult result =  new StreamResult(libraryFile);
                transformer.transform(source, result);
            } catch (Exception ex) {
                YAYManView.logger.severe("Error writing library XML file: "+libraryFile.getPath()+", error: "+ex);
            }
        }
        cancelClose();
    }

    @Action
    public void removeLibraryDir() {
        if (libList.getModel().getSize() > 0 && libList.getSelectedIndex() != -1) {
            libs.remove(libList.getSelectedIndex());
        }
    }

    @Action
    public void addLibraryDir() {
        /*String playerPath = playerPathTxt.getText();
       
        if (playerPath != null && !playerPath.isEmpty()) {
            NMTLibrary libObj = new NMTLibrary(pathTxt.getText(), playerPath, excludeNames, descTxt.getText());
            libs.addElement(libObj);
            pathTxt.setText("");
            descTxt.setText("");
        }*/
        NMTLibrary lib = new NMTLibrary("", "", "", "New Folder");
        ((DefaultListModel)libList.getModel()).addElement(lib);
        libList.setSelectedIndex(libList.getModel().getSize()-1);
        descTxt.setText("");
    }
    
    @Action
    public void saveLibraryDir() {
        if (pathTxt.getText() == null || pathTxt.getText().isEmpty() || playerPathTxt.getText() == null || playerPathTxt.getText().isEmpty()) {
            //JOptionPane.showMessageDialog(this, "Are you sure you want to delete this movie ID?", "Confirm Delete", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
            JOptionPane.showMessageDialog(this, "You must set both the Local Path and the Player Path", "Path not set", JOptionPane.WARNING_MESSAGE);
            return;
        }
        NMTLibrary lib = (NMTLibrary)libList.getSelectedValue();
        lib.setDescription(descTxt.getText());
        lib.setPath(pathTxt.getText());
        lib.setPlayerPath(playerPathTxt.getText());
    }

    @Action
    public void selectDirectory() {
        if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            String path = fileChooser.getSelectedFile().getPath();
            if (path.startsWith("//") && !path.startsWith("////")) path = "//"+path;
            pathTxt.setText(path);
            if (radiHome.isSelected() || radPC.isSelected()) togglePlayerPathOptions();
        }
    }

    public boolean isValidLibraryFile(File libFile) {
        libraryFile = libFile;
        if (!libraryFile.exists()) return false;
        try {
            loadLibrary();
        } catch (Exception ex) {
            return false;
        }
        return true;
    }

    private void showComponentPopup(JComponent comp, java.awt.event.MouseEvent evt) {
        javax.swing.JPopupMenu menu = comp.getComponentPopupMenu();
        if (menu != null) {
            menu.show(comp, evt.getX(), evt.getY());
        }
    }

    @Action
    public void togglePlayerPathOptions() {
        cmbUSB.setEnabled(false);
        cmbHD.setEnabled(false);
        cmbNetwork.setEnabled(false);
        String playerPath = null;
        if (radiHome.isSelected()) {
            playerPath = "/action/jukebox.jsp?absolutepath=" + pathTxt.getText();
            if (!playerPath.endsWith("/")) {
                playerPath = playerPath + "/";
            }
        } else if (radUSB.isSelected()) {
            cmbUSB.setEnabled(true);
            playerPath = "file:///opt/sybhttpd/localhost.drives/"+cmbUSB.getSelectedItem().toString()+"/";
        } else if (radNetwork.isSelected()) {
            cmbNetwork.setEnabled(true);
            playerPath = "file:///opt/sybhttpd/localhost.drives/NETWORK_SHARE/"+cmbNetwork.getSelectedItem().toString()+"/";
        } else if (radHD.isSelected()) {
            cmbHD.setEnabled(true);
            playerPath = "file:///opt/sybhttpd/localhost.drives/"+cmbHD.getSelectedItem().toString()+"/";
        } else if (radPC.isSelected()) {
            //playerPath = "file:///"+pathTxt.getText().replace("\\", "/");
            playerPath = playerPathTxt.getText();
        } else if (radEvUSB.isSelected()) {
            playerPath = "ev-usb://"+cmbEvUSB.getSelectedItem().toString();
        }

        if (helpPlayerPath) playerPathTxt.setText(playerPath);
    }

    public void setOptionsFromIP() {
        new MySwingWorker() {
            @Override
            protected Void doInBackground() {
                setHDFromIP();
                setNetworkFromIP();
                return null;
            }
        }.execute();
    }

    public void setHDFromIP() {
        DefaultComboBoxModel hdModel = new DefaultComboBoxModel();
        DefaultComboBoxModel usbModel = new DefaultComboBoxModel();
        DefaultComboBoxModel evModel = new DefaultComboBoxModel();
        try {
            Document doc = popAPI.getDevices();
            if (popAPI.querySuccess(doc)) {
                NodeList nl = doc.getElementsByTagName("device");
                for (int i = 0; i < nl.getLength(); i++) {
                    Element deviceEle = (Element)nl.item(i);
                    String accessPath = deviceEle.getElementsByTagName("accessPath").item(0).getTextContent();
                    String type = deviceEle.getElementsByTagName("type").item(0).getTextContent();
                    if (type.equals("usb")) {
                        usbModel.addElement(accessPath);
                        String usbName = deviceEle.getElementsByTagName("name").item(0).getTextContent();
                        evModel.addElement(usbName);
                    } else {
                        hdModel.addElement(accessPath);
                    }
                }
            }
        } catch (Exception ex) {
            YAYManView.logger.severe("Error setting hard disk options from NMT IP ("+nmtIP+"): "+ex);
        }
        
        if (hdModel.getSize() > 0) cmbHD.setModel(hdModel);
        if (usbModel.getSize() > 0) cmbUSB.setModel(usbModel);
        if (evModel.getSize() > 0) cmbEvUSB.setModel(evModel);
    }

    public void setNetworkFromIP() {
        DefaultComboBoxModel netModel = new DefaultComboBoxModel();
        try {
            Document doc = popAPI.getShares();
            if (popAPI.querySuccess(doc)) {
                NodeList nl = doc.getElementsByTagName("networkShare");
                for (int i = 0; i < nl.getLength(); i++) {
                    Element shareEle = (Element)nl.item(i);
                    String shareName = shareEle.getElementsByTagName("shareName").item(0).getTextContent();
                    netModel.addElement(shareName);
                }
            } 
        } catch (Exception ex) {
            YAYManView.logger.severe("Error setting HD options from NMT IP ("+nmtIP+"): "+ex);
        }
        
        if (netModel.getSize() > 0) cmbNetwork.setModel(netModel);
    }
    
    public List<NMTLibrary> getLibraries() {
        List<NMTLibrary> libraryList = new ArrayList();
        ListModel model = libList.getModel();
        for (int i = 0; i < model.getSize(); i ++) {
            NMTLibrary lib = (NMTLibrary)model.getElementAt(i);
            libraryList.add(lib);
        }
        return libraryList;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem addDirMenu;
    private javax.swing.JButton btnSaveDir;
    private javax.swing.JButton cancelBtn;
    private javax.swing.JComboBox cmbEvUSB;
    private javax.swing.JComboBox cmbHD;
    private javax.swing.JComboBox cmbNetwork;
    private javax.swing.JComboBox cmbUSB;
    private javax.swing.JTextField descTxt;
    private javax.swing.JFileChooser fileChooser;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JList libList;
    private javax.swing.JPopupMenu libraryMenu;
    private javax.swing.JPopupMenu myiHomePop;
    private javax.swing.JMenuItem myiHomePopChooseMenu;
    private javax.swing.JTextField pathTxt;
    private javax.swing.ButtonGroup pathTypeGroup;
    private javax.swing.JTextField playerPathTxt;
    private javax.swing.JRadioButton radEvUSB;
    private javax.swing.JRadioButton radHD;
    private javax.swing.JRadioButton radNetwork;
    private javax.swing.JRadioButton radPC;
    private javax.swing.JRadioButton radUSB;
    private javax.swing.JRadioButton radiHome;
    private javax.swing.JMenuItem removeDirMenu;
    private javax.swing.JButton saveBtn;
    // End of variables declaration//GEN-END:variables

}
